package cn.xsly.basic.util;

import cn.xsly.basic.jwt.JwtUtils;
import cn.xsly.basic.jwt.LoginData;
import cn.xsly.basic.jwt.Payload;
import cn.xsly.basic.jwt.RsaUtils;
import cn.xsly.user.domain.Logininfo;
import org.junit.platform.commons.function.Try;

import javax.servlet.http.HttpServletRequest;
import java.security.PublicKey;

public class LoginContext {
    public static Logininfo getLogininfo(HttpServletRequest request) {
        try {
            String jwtToken = request.getHeader("token");
            if (jwtToken != null) {
                //获取公钥
                PublicKey publicKey = RsaUtils.getPublicKey(JwtUtils.class.getClassLoader().getResource("auth_rsa.pub").getFile());
                //解密
                Payload<LoginData> payload = JwtUtils.getInfoFromToken(jwtToken, publicKey, LoginData.class);
                //读取荷载的数据
                Logininfo logininfo = payload.getLoginData().getLogininfo();
                return logininfo;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
